package com.zhuangjie.mvc.ws.utils;

import com.alibaba.nacos.common.packagescan.resource.AntPathMatcher;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 路径变量工具
 *
 * @author zhuangjie
 * @date 2024/01/26
 */
public class PathVarUtils {
    /**
     * 是否匹配
     *
     * @param compatiblePath 兼容路径 如：/user/{id}
     * @param actualPath     实际路径 “/user/123”
     * @return boolean
     */
    public static boolean isMate(String compatiblePath, String actualPath) {
        final String regex = "\\{[^\\{\\}]*\\}";
        final String subst = "*";
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(compatiblePath);
        final String genericPath = matcher.replaceAll(subst);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.match(genericPath, actualPath);
    }

    /**
     * 获取路径变量
     *
     * @param compatiblePath 兼容路径
     * @param actualPath     实际路径
     * @return {@link Map}<{@link String}, {@link String}>
     */
    public static Map<String, String> getPathVars(String compatiblePath, String actualPath) {
        Map<String, String> variables = new AntPathMatcher().extractUriTemplateVariables(compatiblePath, actualPath);
        return variables;
    }

//    public static void main(String[] args) {
//        Map<String, String> pathVars = getPathVars("/user/{id}", "/user/123");
//        System.out.println(pathVars);
//    }
}
